package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"gitee.com/lovehei/gostudy/examples/ent/ent"
	"gitee.com/lovehei/gostudy/examples/ent/ent/user"

	// 初始化数据库
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	db, err := initializeDB()
	client := db.Client

	if err != nil {
		log.Fatalf("failed opening connection to mysql:%v", err)
	}

	defer client.Close()

	if err := client.Schema.Create(context.Background()); err != nil {
		log.Fatalf("failed creatinig schema resources: %v", err)
	}
	user, err := CreateUser(context.Background(), client)
	if err != nil {
		log.Fatal(err, user)
	}
	user, err = QueryUser(context.Background(), client)
	if err != nil {
		log.Fatal(err)
	}

}

// CreateUser createuser
func CreateUser(ctx context.Context, client *ent.Client) (*ent.User, error) {
	u, err := client.User.Create().
		SetName("a8m").
		SetCreateTime(time.Now()).
		Save(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed createing user: %v", err)
	}

	log.Println("user was created", u)
	return u, nil
}

// QueryUser queryuser
func QueryUser(ctx context.Context, client *ent.Client) (*ent.User, error) {
	u, err := client.User.
		Query().
		Where(user.NameEQ("a8m11")).
		// `Only` 会查询失败，
		// 当未找到用户或找到多个（大于一个）用户时，
		Only(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed querying user: %v", err)
	}
	log.Println("user returned: ", u)
	return u, nil
}
